<?php

class ectools_refund extends ectools_operation {

    public function __construct($app) {
        $this->app = $app;
    }

    final public function __clone() {
        trigger_error(app::get('ectools')->_("此类对象不能被克隆！"), E_USER_ERROR);
    }

    public function generate(&$sdf, &$controller = null, &$msg = '') {
        // 异常处理
        if (! isset($sdf) || ! $sdf || ! is_array($sdf)) {
            trigger_error(app::get('ectools')->_("退款单信息不能为空！"), E_USER_ERROR);
            exit();
        }
        
        $is_save = false;
        
        // 保存的接口方法
        $obj_refund_create = kernel::single("ectools_refund_create");
        $is_save = $obj_refund_create->generate($sdf);
        
        if (! $is_save) {
            $msg = app::get('ectools')->_('退款单生成失败！');
            return false;
        }
        
        $obj_refund_special = kernel::servicelist('ectools_refund.ectools_mdl_special_refund');
        foreach ($obj_refund_special as $obj_app) {
            $is_save = $obj_app->dorefund($sdf);
        }
        
        // 在线支付原路退款
        if ($sdf['pay_app_id'] != 'deposit') {
            // 获取成功支付的单子
            $orderBillsMdl = app::get('ectools')->model('order_bills');
            $paymentsMdl = app::get('ectools')->model('payments');
            $orderBills = $orderBillsMdl->getList('bill_id', array(
                'rel_id' => $sdf['order_id']
            ));
            
            if (function_exists('array_column')) {
                $payment_id = array_column($orderBills, 'bill_id');
            } else {
                $payment_id = $this->array_column($orderBills, 'bill_id');
            }
            
            $payment = $paymentsMdl->getRow('payment_id', array(
                'payment_id' => $payment_id,
                'status' => 'succ'
            ));
            $sdf['payment_id'] = $payment['payment_id'];
            $is_save = $this->dorefund($sdf, $msg);
        }
        
        if ($is_save) {
            $obj_api_refund = kernel::single("ectools_refund_update");
            $sdf['status'] = 'succ';
            $is_save = $obj_api_refund->generate($sdf);
            
            if (! $is_save) {
                $msg = app::get('ectools')->_('退款单编辑失败！');
                return false;
            }
        }
        
        return $is_save;
    }

    // 在线支付订单原路退回
    public function dorefund($sdf, &$msg) {
        // 校验订单是否可以原路退回
        $result = true;
        switch ($sdf['pay_app_id']) {
            case 'wxpayjsapi':
            case 'wxpaywxapp':
                $result = kernel::single('weixin_refund_plugin_wxpay')->dorefund($sdf, $msg);
                break;
        }
        return $result;
    }
}

?>
